//
//  SDNSString.m
//  SKinDiary
//
//  Created by pcyang on 16/6/26.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "SDNSString.h"

BOOL IsEffectiveString(NSString *originalStr)
{
    if (originalStr && [originalStr isKindOfClass:[NSString class]] && originalStr.length > 0)
    {
        return YES;
    }
    
    return NO;
}

NSString* GetSafeString(NSString *originalStr)
{
    if (originalStr && [originalStr isKindOfClass:[NSString class]])
    {
        return originalStr;
    }
    
    return @"";
}


static inline NSDateFormatter * dateFormatter()
{
    static NSDateFormatter * g_DateFormatter = nil;
    if (!g_DateFormatter) {
        g_DateFormatter = [[NSDateFormatter alloc] init];
        g_DateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    }
    return g_DateFormatter;
}

@implementation SDNSString


+(NSString*) stringFromDate:(NSDate*)date
{
    int pubdate = [date timeIntervalSince1970];
    
    struct tm* pubDate = localtime((const time_t*)&pubdate);
    
    struct tm stPubDate = *pubDate;
    
    int yearOfPubDate = pubDate->tm_year + 1900;
    int monOfPubDate = pubDate->tm_mon + 1;
    int dayOfPubDate = pubDate->tm_mday;
    int hourOfPubDate = pubDate->tm_hour;
    int minOfPubDate = pubDate->tm_min;
    //int secOfPubDate = pubDate->tm_sec;
    
    time_t now = time(0);
    
    struct tm* today = localtime((const time_t*)&now);
    int yearOfToday = today->tm_year + 1900;
    int dayOfToday = today->tm_mday;
    
    int times = (int)now - pubdate;
    if (times < 0)
    {
        times = -times;
    }
    
    NSString* s = nil;
    
    
    if (times >= 0 && times < 60)
    {
        s = [NSString stringWithFormat:@"刚刚"];
    }
    else if (times >= 60 && times < 60 * 60)
    {
        s = [NSString stringWithFormat:@"%d分钟前", times / 60];
    }
    else if (times >= 60 * 60 && times < 60 * 60 * 24)
    {
        if (dayOfToday != dayOfPubDate)
        {
            //s = [NSString stringWithFormat:@"昨天 %02d:%02d:%02d", hourOfPubDate, minOfPubDate, secOfPubDate];
            s = [NSString stringWithFormat:@"昨天%02d:%02d", hourOfPubDate, minOfPubDate];
        }
        else
        {
            s = [NSString stringWithFormat:@"%d小时前", times / (60 * 60)];
        }
    }
    else if (times >= 60 * 60 * 24 && times < 60 * 60 * 24 * 2)
    {
        if (dayOfToday - dayOfPubDate == 1)
        {
            //s = [NSString stringWithFormat:@"昨天 %02d:%02d:%02d", hourOfPubDate, minOfPubDate, secOfPubDate];
            s = [NSString stringWithFormat:@"昨天%02d:%02d", hourOfPubDate, minOfPubDate];
        }
        else if (dayOfToday - dayOfPubDate > 1)
        {
            //s = [NSString stringWithFormat:@"前天 %02d:%02d:%02d", hourOfPubDate, minOfPubDate, secOfPubDate];
            s = [NSString stringWithFormat:@"前天%02d:%02d", hourOfPubDate, minOfPubDate];
        }
        else
        {
            s = [NSString stringWithFormat:@"%d年%d月%d日", yearOfPubDate, monOfPubDate, dayOfPubDate];
        }
    }
    else if (times >= 60 * 60 * 24 * 2 && times < 60 * 60 * 24 * 3)
    {
        if (dayOfToday - dayOfPubDate == 2)
        {
            //s = [NSString stringWithFormat:@"前天 %02d:%02d:%02d", hourOfPubDate, minOfPubDate, secOfPubDate];
            s = [NSString stringWithFormat:@"前天%02d:%02d", hourOfPubDate, minOfPubDate];
        }
        else if (dayOfToday - dayOfPubDate > 2)
        {
            if (yearOfToday != yearOfPubDate)
            {
                s = [NSString stringWithFormat:@"%d年%d月%d日", yearOfPubDate, monOfPubDate, dayOfPubDate];
            }
            else
            {
                /*
                 s = [NSString stringWithFormat:@"%d月%d日 %02d:%02d:%02d",
                 stPubDate.tm_mon + 1,
                 stPubDate.tm_mday,
                 stPubDate.tm_hour,
                 stPubDate.tm_min,
                 secOfPubDate];
                 */
                s = [NSString stringWithFormat:@"%d月%d日%02d:%02d",
                     stPubDate.tm_mon + 1,
                     stPubDate.tm_mday,
                     stPubDate.tm_hour,
                     stPubDate.tm_min];
            }
        }
        else
        {
            s = [NSString stringWithFormat:@"%d年%d月%d日", yearOfPubDate, monOfPubDate, dayOfPubDate];
        }
    }
    else if (times >= 60 * 60 * 24 * 3)
    {
        if (yearOfToday != yearOfPubDate)
        {
            s = [NSString stringWithFormat:@"%d年%d月%d日", yearOfPubDate, monOfPubDate, dayOfPubDate];
        }
        else
        {
            /*
             s = [NSString stringWithFormat:@"%d月%d日 %02d:%02d:%02d",
             stPubDate.tm_mon + 1,
             stPubDate.tm_mday,
             stPubDate.tm_hour,
             stPubDate.tm_min,
             secOfPubDate];
             */
            s = [NSString stringWithFormat:@"%d月%d日%02d:%02d",
                 stPubDate.tm_mon + 1,
                 stPubDate.tm_mday,
                 stPubDate.tm_hour,
                 stPubDate.tm_min];
        }
    }
    
    return s;
}

+ (NSString*)shortStringFromDate:(NSDate *)date
{
    int pubdate = [date timeIntervalSince1970];
    time_t now = time(0);
    
    int times = (int)now - pubdate;
    if (times < 0)
    {
        times = -times;
    }
    
    NSString* s = nil;
    
    
    if (times >= 0 && times < 60)
    {
        s = [NSString stringWithFormat:@"刚刚"];
    }
    else if (times >= 60 && times < 60 * 60)
    {
        s = [NSString stringWithFormat:@"%d分钟前", times / 60];
    }
    else
    {
        //s = [QSUtil NSDateToNSString:date dateFormat:@"HH:mm"];
        s = [date formattedStringWithFormat:@"HH:mm"];
    }
    
    
    return s;
}

+ (NSString*) simpleStringFromDate:(NSDate *)date
{
    int pubdate = [date timeIntervalSince1970];
    
    struct tm* pubDate = localtime((const time_t*)&pubdate);
    
    struct tm stPubDate = *pubDate;
    
    int yearOfPubDate = pubDate->tm_year + 1900;
    int monOfPubDate = pubDate->tm_mon + 1;
    int dayOfPubDate = pubDate->tm_mday;
    
    time_t now = time(0);
    
    struct tm* today = localtime((const time_t*)&now);
    int yearOfToday = today->tm_year + 1900;
    int dayOfToday = today->tm_mday;
    
    int times = (int)now - pubdate;
    if (times < 0)
    {
        times = -times;
    }
    
    NSString* s = nil;
    
    
    if (times >= 0 && times < 60)
    {
        s = [NSString stringWithFormat:@"刚刚"];
    }
    else if (times >= 60 && times < 60 * 60)
    {
        s = [NSString stringWithFormat:@"%d分钟前", times / 60];
    }
    else if (times >= 60 * 60 && times < 60 * 60 * 24)
    {
        if (dayOfToday != dayOfPubDate)
        {
            s = [NSString stringWithFormat:@"昨天"];
        }
        else
        {
            s = [NSString stringWithFormat:@"%d小时前", times / (60 * 60)];
        }
    }
    else if (times >= 60 * 60 * 24 && times < 60 * 60 * 24 * 2)
    {
        if (dayOfToday - dayOfPubDate == 1)
        {
            s = [NSString stringWithFormat:@"昨天"];
        }
        else if (dayOfToday - dayOfPubDate > 1)
        {
            s = [NSString stringWithFormat:@"前天"];
        }
        else
        {
            s = [NSString stringWithFormat:@"%d年%d月%d日", yearOfPubDate, monOfPubDate, dayOfPubDate];
        }
    }
    else if (times >= 60 * 60 * 24 * 2 && times < 60 * 60 * 24 * 3)
    {
        if (dayOfToday - dayOfPubDate == 2)
        {
            s = [NSString stringWithFormat:@"前天"];
        }
        else if (dayOfToday - dayOfPubDate > 2)
        {
            if (yearOfToday != yearOfPubDate)
            {
                s = [NSString stringWithFormat:@"%d年%d月%d日", yearOfPubDate, monOfPubDate, dayOfPubDate];
            }
            else
            {
                s = [NSString stringWithFormat:@"%d月%d日",
                     stPubDate.tm_mon + 1,
                     stPubDate.tm_mday];
            }
        }
        else
        {
            s = [NSString stringWithFormat:@"%d年%d月%d日", yearOfPubDate, monOfPubDate, dayOfPubDate];
        }
    }
    else if (times >= 60 * 60 * 24 * 3)
    {
        if (yearOfToday != yearOfPubDate)
        {
            s = [NSString stringWithFormat:@"%d年%d月%d日", yearOfPubDate, monOfPubDate, dayOfPubDate];
        }
        else
        {
            s = [NSString stringWithFormat:@"%d月%d日",
                 stPubDate.tm_mon + 1,
                 stPubDate.tm_mday];
        }
    }
    
    return s;
    
}
+(NSString*)getTimeStringFromDate:(NSDate*)date
{
    int pubdate = [date timeIntervalSince1970];
    
    struct tm* pubDate = localtime((const time_t*)&pubdate);
    
    int yearOfPubDate = pubDate->tm_year + 1900;
    int monOfPubDate = pubDate->tm_mon + 1;
    int dayOfPubDate = pubDate->tm_mday;
    
    time_t now = time(0);
    
    int times = (int)now - pubdate;
    if (times < 0)
    {
        times = -times;
    }
    
    NSString* s = nil;
    
    
    if (times >= 0 && times < 60)
    {
        s = [NSString stringWithFormat:@"刚刚"];
    }
    else if (times >= 60 && times < 60 * 60)    //1分钟前
    {
        s = [NSString stringWithFormat:@"%d分钟前", times / 60];
    }
    else if (times >= 60 * 60 && times < 60 * 60 * 3)       //3小时前
    {
        s = [NSString stringWithFormat:@"%d小时前", times / (60 * 60)];
    }
    else if (times >= 60 * 60 * 3 && times < 60 * 60 * 24)
    {
        //s = [QSUtil NSDateToNSString:date dateFormat:@"yyyy-MM-dd HH:mm"];
        s = [date formattedStringWithFormat:@"yyyy-MM-dd HH:mm"];
    }
    else if (times >= 60 * 60 * 24)
    {
        s = [NSString stringWithFormat:@"%d年%d月%d日", yearOfPubDate, monOfPubDate, dayOfPubDate];
    }
    
    return s;
}


+(NSString*)getTimeStringFromDateString:(NSString*)dateString
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy/MM/dd/"];

    NSDate *date = [formatter dateFromString:dateString];
   return [date formattedStringWithFormat:@"yyyy年MM月dd日"];
}

+(NSString*)getTimeStringFromDateString:(NSString*)dateString formatterString:(NSString*)formatterString
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
     [formatter setDateFormat:formatterString];
    
    NSDate *date = [formatter dateFromString:dateString];
    return [date formattedStringWithFormat:@"yyyy年MM月dd日"];
}

@end

@implementation NSString (VPEncode)

- (NSString*)MD5EncodedString
{
    return [[self dataUsingEncoding:NSUTF8StringEncoding] MD5EncodedString];
}

- (NSString*)URLEncodedString
{
    return [self URLEncodedStringWithCFStringEncoding:kCFStringEncodingUTF8];
}

- (NSString*)URLDecodedString
{
    return [self URLDecodedStringWithCFStringEncoding:kCFStringEncodingUTF8];
}

- (NSString*)URLEncodedStringWithCFStringEncoding:(CFStringEncoding)encoding
{
    return CFBridgingRelease( CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef)self, NULL, CFSTR("￼=,!$&'()*+;@?\n\"<>#\t :/"),encoding) );
}

- (NSString*)URLDecodedStringWithCFStringEncoding:(CFStringEncoding)encoding
{
    return CFBridgingRelease( CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)self, CFSTR("￼"),encoding) );
}


@end


@implementation NSObject (VPEncode)
- (NSString*)MD5EncodedString
{
    NSData* data = nil;
    if( [self isKindOfClass:[NSData class]] )
        data = (NSData*)self;
    else if( [self respondsToSelector:@selector(dataUsingEncoding:)] )
        data = [(NSString*)self dataUsingEncoding:NSUTF8StringEncoding];
    
    if( data )return [data MD5EncodedString];
    else return nil;
}
@end


@implementation NSString (Color)

- (UIColor *)toUIColor {
    //    unsigned int c;
    //    if ([self characterAtIndex:0] == '#' ) {
    //        [[NSScanner scannerWithString:[self substringFromIndex:1]] scanHexInt:&c];
    //    } else {
    //        [[NSScanner scannerWithString:self] scanHexInt:&c];
    //    }
    //    return [UIColor colorWithRed:((c & 0xff0000) >> 16)/255.0 green:((c & 0xff00) >> 8)/255.0 blue:(c & 0xff)/255.0 alpha:1.0];
    
    if ( !self.length ) {
        return nil;
    }
    
    unsigned int c;
    bool isRGBA = NO;
    if ([self characterAtIndex:0] == '#' ) {
        isRGBA = (self.length == 9);
        [[NSScanner scannerWithString:[self substringFromIndex:1]] scanHexInt:&c];
    } else {
        isRGBA = (self.length == 8);
        [[NSScanner scannerWithString:self] scanHexInt:&c];
    }
    
    //这里兼容一下android那边的ARGB （-。-）！ Norcy(20150824)
    if ( isRGBA ) {
        return [UIColor colorWithRed:((c & 0xff0000) >> 16)/255.0 green:((c & 0xff00) >> 8)/255.0 blue:(c & 0xff)/255.0 alpha:((c & 0xff000000) >> 24)/255.0];
    } else {
        return [UIColor colorWithRed:((c & 0xff0000) >> 16)/255.0 green:((c & 0xff00) >> 8)/255.0 blue:(c & 0xff)/255.0 alpha:1.0];
    }
}

@end


@implementation NSString (VPNumber)
- (char)charValue
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    NSNumber* num = [numberFormatter numberFromString:self];
    return [num charValue];
}

- (unsigned char)unsignedCharValue
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    NSNumber* num = [numberFormatter numberFromString:self];
    return [num unsignedCharValue];
}

- (short)shortValue
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    NSNumber* num = [numberFormatter numberFromString:self];
    return [num shortValue];
}

- (unsigned short)unsignedShortValue
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    NSNumber* num = [numberFormatter numberFromString:self];
    return [num unsignedShortValue];
}

- (unsigned int)unsignedIntValue
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    NSNumber* num = [numberFormatter numberFromString:self];
    return [num unsignedIntValue];
}

- (long)longValue
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    NSNumber* num = [numberFormatter numberFromString:self];
    return [num longValue];
}

- (unsigned long)unsignedLongValue
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    NSNumber* num = [numberFormatter numberFromString:self];
    return [num unsignedLongValue];
}

- (unsigned long long)unsignedLongLongValue
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    NSNumber* num = [numberFormatter numberFromString:self];
    return [num unsignedLongLongValue];
}

- (NSUInteger)unsignedIntegerValue
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    NSNumber* num = [numberFormatter numberFromString:self];
    return [num unsignedIntegerValue];
}
@end

@implementation NSString(Image)

/**判断是否是gif文件*/
- (BOOL)isGif
{
    NSString*path=self;
    FILE* fp = fopen([path UTF8String], "r");
    BOOL ifgif = FALSE;
    char Strpre[3] = {0};
    if (fp && fread(Strpre, 1, 3, fp) != EOF) {
        if (Strpre[0] == 'G' && Strpre[1] == 'I' && Strpre[2] == 'F') {
            ifgif = YES;
        }
    }
    if (fp) {
        fclose(fp);
    }
    
    return ifgif;
}

@end

@implementation NSString (HTML)

- (NSString*)stringByRemovingHTMLTags
{
//    TTMarkupStripper* stripper = [[TTMarkupStripper alloc] init];
//    return [stripper parse:self];
    return NULL;
}
@end

@implementation NSString (safe)

- (NSString *)safeString
{
    if ([self isKindOfClass:[NSString class]])
    {
        return (NSString *)self;
    }
    return @"";
}

- (BOOL)isEmptyString
{
    if (0 == self.length)
    {
        return YES;
    }
    
    // 将localString去除所有的空白字符串
    NSString *tmpString = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (0 == [tmpString length])
    {
        return YES;
    }
    
    return NO;
    
}
@end

@implementation NSString(Regex)

- (BOOL)isMatchedByRegex:(NSString *)pattern
{
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    if (error == nil)
    {
        NSUInteger numberOfMatches = [regex numberOfMatchesInString:self
                                                            options:0
                                                              range:NSMakeRange(0, [self length])];
        return (numberOfMatches > 0);
    }
    
    return NO;
}

- (NSString *)stringByRegex:(NSString *)pattern
{
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
    
    if (! error)
    {
        NSTextCheckingResult *firstMatch = [regex firstMatchInString:self options:0 range:NSMakeRange(0, [self length])];
        if (firstMatch)
        {
            NSRange resultRange = [firstMatch rangeAtIndex:0];
            return [self substringWithRange:resultRange];
        }
    }
    
    return @"";
}

- (NSString *)stringByReplacingOccurrencesOfRegex:(NSString *)pattern withTemplate:(NSString *)templateString
{
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    if (error == nil)
    {
        NSString *newString = [regex stringByReplacingMatchesInString:self
                                                              options:0
                                                                range:NSMakeRange(0, [self length])
                                                         withTemplate:templateString];
        return newString;
    }
    
    return self;
}

@end

@implementation NSString (Contains)

- (BOOL)myContainsString:(NSString*)other {
    NSRange range = [self rangeOfString:other];
    return range.length != 0;
}

@end

@implementation NSString (Escape)

- (NSString *)escapeString
{
    NSString *tempStr = [self stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    tempStr = [tempStr stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    tempStr = [tempStr stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    
    return tempStr;
    
}
@end

@implementation NSString (keyVals)

-(NSDictionary*) getKeyValMap
{
    NSMutableDictionary* tmpDict = [[NSMutableDictionary alloc] initWithCapacity:6];
    NSArray* itemArr = [self componentsSeparatedByString:@"&"];
    
    for(NSString* item in itemArr)
    {
        NSArray* keyValue = [item componentsSeparatedByString:@"="];
        if(2==keyValue.count)
        {
            NSString* key = [[keyValue objectAtIndex:0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            NSString* val = [[keyValue objectAtIndex:1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            
            if(key && val && key.length>0 && val.length>0)
                [tmpDict setObject:val forKey:key];
        }
    }
    
    return tmpDict;
}

@end

@implementation NSString (Url)

-(NSDictionary*) getParams
{
    NSRange range = [self rangeOfString:@"?"];
    
    if (NSNotFound==range.location)
    {
    }
    else if(self.length>(range.location+1))
    {
        NSString* subStr = [self substringFromIndex:range.location+1];
        return [subStr getKeyValMap];
    }
    
    return nil;
}

-(NSString*) getBaseUrl
{
    NSRange range = [self rangeOfString:@"?"];
    
    if (NSNotFound==range.location)
    {
        return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    }
    else
    {
        NSString* url = [self substringToIndex:range.location];
        return [url stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    }
}

-(NSString*) urlByaddParams:(NSDictionary*) params
{
    BOOL isNeedAdd = NO;
    NSMutableString* newUrl = [NSMutableString stringWithString:self];
    
    NSRange range = [newUrl rangeOfString:@"?"];
    if (NSNotFound == range.location)
    {
        [newUrl appendString:@"?"];
    }
    else
    {
        NSDictionary* dict = [newUrl getParams];
        if (dict.count>0)
        {
            isNeedAdd = YES;
        }
    }
    
    NSArray* keyArr = [params allKeys];
    for(NSInteger index = 0; index<keyArr.count; ++index)
    {
        NSString* key = [keyArr objectAtIndex:index];
        NSString* val = [params objectForKey:key];
        
        if (key && val)
        {
            if(0==index && NO==isNeedAdd)
                [newUrl appendString:[NSString stringWithFormat:@"%@=%@",key, val]];
            else
                [newUrl appendString:[NSString stringWithFormat:@"&%@=%@",key, val]];
        }
    }
    
    return newUrl;
}
@end


@implementation NSString (Util)

- (CGSize)sizeWithFont:(UIFont *) font
{
    NSDictionary *fontAsAttributes = @{NSFontAttributeName:font};
    return [self sizeWithAttributes:fontAsAttributes];
}

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size
{
    NSDictionary *fontAsAttributes = @{NSFontAttributeName:font};
    CGRect retVal = [self boundingRectWithSize:size
                                       options:NSStringDrawingUsesLineFragmentOrigin
                                    attributes:fontAsAttributes context:nil];
    return retVal.size;
}


- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode
{
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self];
    
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    [paragraphStyle setLineBreakMode:lineBreakMode];
    [attributedString setAttributes:@{NSParagraphStyleAttributeName:paragraphStyle} range:NSMakeRange(0, attributedString.length)];
    [attributedString setAttributes:@{NSFontAttributeName:font} range:NSMakeRange(0, attributedString.length)];
    
    CGRect retVal = [attributedString boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin context:nil];
    return retVal.size;
}

@end


@implementation NSString (Random)

+ (NSString *)randomAlphanumericStringWithLength:(NSInteger)length
{
    NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    NSMutableString *randomString = [NSMutableString stringWithCapacity:length];
    
    for (int i = 0; i < length; i++) {
        [randomString appendFormat:@"%C", [letters characterAtIndex:arc4random() % [letters length]]];
    }
    
    return randomString;
}

+ (NSString *)randomAlphanumericWithLength:(NSInteger)length
{
    NSString *letters = @"0123456789";
    NSMutableString *randomString = [NSMutableString stringWithCapacity:length];
    
    for (int i = 0; i < length; i++) {
        [randomString appendFormat:@"%C", [letters characterAtIndex:arc4random() % [letters length]]];
    }
    
    return randomString;
}
@end
